package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.pojo.Ossproperites;
import com.itheima.pojo.Result;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.content.image.png;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
@Slf4j
@Log4j2
public class CommonController {
    @Autowired
    private Ossproperites ossproperites;

    @PostMapping("/upload")

    // public Result upload() {
    //     return new Result(null,null,null);
    // }
    public Result upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
// 创建OSSClient实例。
        OSS ossClient = new
                OSSClientBuilder().build(ossproperites.getEndpoint(),
                ossproperites.getAccessKey(), ossproperites.getSecret());
        try {
            ossClient.putObject(ossproperites.getBucketName(), fileName, new
                    ByteArrayInputStream(file.getBytes()));
        } catch (Exception oe) {
            log.error("上传文件异常");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return new Result(1, "上传成功", ossproperites.getUrl() + "/" + fileName, "{}");

}
}